package com.webdrider.manager.action.blog;

import java.util.List;

import com.common.dao.interfaces.IDao;
import com.common.dao.util.Criteria;
import com.common.manager.abstracts.AbstractManager;
import com.common.security.exceptions.DatabaseException;
import com.common.security.exceptions.ManagerException;
import com.webdrider.dao.action.blog.PostDao;
import com.webdrider.dao.interfaces.IPostDao;
import com.webdrider.manager.interfaces.IPostManager;
import com.webdrider.model.action.blog.Post;
import com.webdrider.security.exceptions.BlogException;

public class PostManager extends AbstractManager<Post> implements IPostManager {

	private IPostDao postDao;
	
	public PostManager() {
		postDao = new PostDao();
	}
	
	@Override
	protected IDao<Post> getDao() {
		return postDao;
	}
	
	@Override
	public Post getPost(String urlTitle) throws BlogException, ManagerException {
		try {
			Criteria criteria = new Criteria(Post.URL_TITLE, urlTitle, true);
			List<Post> posts = postDao.getByCriteria(criteria);
			
			if (posts.size() == 0) {
				throw new BlogException(BlogException.POST_NOT_FOUND);
			} else if (posts.size() == 1) {
				return posts.get(0);
			} else {
				throw new BlogException(BlogException.MULTIPLE_POSTS_FOUND);
			}
		} catch (DatabaseException e) {
			throw new ManagerException(ManagerException.DATABASE_EXCEPTION);
		}
	}

	@Override
	public void save(Post post) throws ManagerException {
		//FIXME Critical priority: Add a map for comments and categories
		post.setUrlTitle(convertUrlTitle(post.getTitle()));
		super.save(post);
	}

	@Override
	public Post getLatestPost() throws BlogException, ManagerException {
		// TODO Auto-generated method stub
		return null;
	}
	
	private String convertUrlTitle(String title) {
		String insensitiveTitle = title.replaceAll("[,!?<>\'\"]", "");
		insensitiveTitle = insensitiveTitle.replace(' ', '_');
		return insensitiveTitle.toLowerCase();
	}
}
